package com.kehutong.auth.util;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.StringTokenizer;

/**
* 功能描述：转换工具类
* @author  MaoShanBo
*/
public class IPUtil {

   private static StringBuilder sb = new StringBuilder();

   public static byte[] getIpByteArrayFromString(String ip) {

       byte[] ret = new byte[4];
       StringTokenizer st = new StringTokenizer(ip, ".");
       try {
           ret[0] = (byte)(Integer.parseInt(st.nextToken()) & 0xFF);
           ret[1] = (byte)(Integer.parseInt(st.nextToken()) & 0xFF);
           ret[2] = (byte)(Integer.parseInt(st.nextToken()) & 0xFF);
           ret[3] = (byte)(Integer.parseInt(st.nextToken()) & 0xFF);
       } catch (Exception e) {

       }
       return ret;
   }

   /**
    * 功能描述 IP数组转换成字符串
    */
   public static String getIpStringFromBytes(byte[] ip) {

       sb.delete(0, sb.length());
       sb.append(ip[0] & 0xFF);
       sb.append('.');
       sb.append(ip[1] & 0xFF);
       sb.append('.');
       sb.append(ip[2] & 0xFF);
       sb.append('.');
       sb.append(ip[3] & 0xFF);
       return sb.toString();
   }

   /**
    * 功能描述：根据某种编码方式将字节数组转换成字符串
    */
   public static String getString(byte[] b, int offset, int len, String encoding) {

       try {
           return new String(b, offset, len, encoding);
       } catch (UnsupportedEncodingException e) {
           return new String(b, offset, len);
       }
   }

    /**
     * 功能描述：获取本地真实的IP地址
     */
    public static String getRealIp() {

        String localip = null;// 本地IP，如果没有配置外网IP则返回它
        String netip = null;// 外网IP

        Enumeration<NetworkInterface> netInterfaces = null;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }

        InetAddress ip = null;
        boolean finded = false;// 是否找到外网IP
        while (netInterfaces.hasMoreElements() && !finded) {

            NetworkInterface ni = netInterfaces.nextElement();
            Enumeration<InetAddress> address = ni.getInetAddresses();
            while (address.hasMoreElements()) {
                ip = address.nextElement();
                if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
                    netip = ip.getHostAddress();
                    finded = true;
                    break;
                } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
                    localip = ip.getHostAddress();
                }
            }
        }

        if (netip != null && !"".equals(netip)) {
            return netip;
        } else {
            return localip;
        }
    }
}